import os
import virtualenv
from addon_manager.addon_logger import AddOnLogger


class VenvWrapper(object):
    __VENV_DIRNAME = ".venv"
    __EXT_PACK_CONFIG_FILE = "ext_package_config.pth"

    def CheckIfExistVenv(self):
        return os.path.exists(self.venvPath)

    def __init__(self, venvBaseDir):
        self.venvPath = os.path.join(venvBaseDir, VenvWrapper.__VENV_DIRNAME)
        self.sitePackagePath = os.path.join(self.venvPath, "lib/python2.7/site-packages")
        self.extPackageConfig = os.path.join(self.sitePackagePath, VenvWrapper.__EXT_PACK_CONFIG_FILE)
        self.__InitTools()

    def CreateVenv(self):
        virtualenv.cli_run([self.venvPath, "--symlink-app-data", "--no-periodic-update"])

    def __InitTools(self):
        bindir = os.path.join(self.venvPath, "bin")
        self.python = os.path.join(bindir, "python")
        self.pip = os.path.join(bindir, "pip")

    def SetModuleSearchPaths(self, paths):
        try:
            with open(self.extPackageConfig, "a+") as config:
                for p in paths:
                    config.write(p + "\n")
        except Exception:
            AddOnLogger().error("SetModuleSearchPath failed !")

    def GetPip(self):
        return self.pip

    def GetPython(self):
        return self.python


__all__ = {"VenvWrapper"}
